<template>
  <div class="update-password-page">
    <!-- 注册表单 -->
    <div class="update-password-container">
      <div class="update-password-box">
        <h2 class="title">修改密码</h2>

        <el-form
          ref="updatePasswordFormRef"
          :model="updatePasswordForm"
          :rules="updatePasswordRules"
          class="update-password-form"
        >
          <el-form-item prop="oldPassword">
            <el-input
              v-model="updatePasswordForm.oldPassword"
              type="password"
              placeholder="请输入旧密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="newPassword">
            <el-input
              v-model="updatePasswordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="updatePasswordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="update-password-btn"
              @click="handleUpdatePassword"
              :loading="loading"
            >
              确认修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElForm } from "element-plus";
import { JSEncrypt } from "jsencrypt";
import {
  updatePasswordAPI,
  getPublicKeyAPI,
  UpdatePasswordType,
} from "@/api/service/user";

const router = useRouter();
const updatePasswordFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(false);
const publicKey = ref("");

// 修改密码表单数据
const updatePasswordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 确认密码验证
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== updatePasswordForm.newPassword) {
    callback(new Error("两次输入的新密码不一致"));
  } else {
    callback();
  }
};

// 表单验证规则
const updatePasswordRules = {
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, max: 20, message: "新密码长度在8到20个字符", trigger: "blur" },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])/,
      message: "新密码必须包含字母、数字和特殊字符",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

// 获取公钥
const getPublicKey = async () => {
  try {
    const response = await getPublicKeyAPI();
    publicKey.value = response as any;
  } catch (error) {
    ElMessage.error("获取加密密钥失败");
  }
};

// 密码加密
const encryptPassword = (password: string) => {
  if (!publicKey.value) {
    ElMessage.error("加密密钥未获取");
    return "";
  }

  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey.value);
  return encrypt.encrypt(password) || "";
};

// 修改密码处理
const handleUpdatePassword = async () => {
  if (!updatePasswordFormRef.value) return;

  await updatePasswordFormRef.value.validate((valid: boolean) => {
    if (valid) {
      updatePassword();
    }
  });
};

const updatePassword = async () => {
  loading.value = true;

  try {
    // 加密密码
    const oldEncryptedPassword = encryptPassword(
      updatePasswordForm.oldPassword
    );
    const newEncryptedPassword = encryptPassword(
      updatePasswordForm.newPassword
    );
    const confirmEncryptedPassword = encryptPassword(
      updatePasswordForm.confirmPassword
    );

    if (
      !oldEncryptedPassword ||
      !newEncryptedPassword ||
      !confirmEncryptedPassword
    ) {
      loading.value = false;
      return;
    }

    // 获取当前用户信息（从 localStorage 或者 store 中获取）
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    if (!userInfo.userCode) {
      ElMessage.error("用户未登录，请先登录");
      router.push("/login");
      loading.value = false;
      return;
    }

    const updateData: UpdatePasswordType = {
      userCode: userInfo.userCode,
      oldEncryptedPassword,
      newEncryptedPassword,
      confirmEncryptedPassword,
    };

    await updatePasswordAPI(updateData);
    ElMessage.success("密码修改成功");
    // 清空表单
    updatePasswordForm.oldPassword = "";
    updatePasswordForm.newPassword = "";
    updatePasswordForm.confirmPassword = "";
  } catch (error: any) {
    if (error) {
      ElMessage.error(error);
    } else {
      ElMessage.error("密码修改失败，请检查网络连接");
    }
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  getPublicKey();
});
</script>

<style scoped lang="scss">
.update-password-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.update-password-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.update-password-box {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  min-width: 400px;
  max-width: 500px;
  width: 100%;

  .title {
    text-align: center;
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 30px;
  }

  .update-password-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-input {
      --el-input-height: 48px;
    }

    .update-password-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
      margin-top: 10px;
    }
  }

  .login-link {
    text-align: center;
    margin-top: 20px;
    color: #666;

    .link {
      color: #409eff;
      text-decoration: none;
      margin-left: 5px;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .banner {
    margin-bottom: 15px;

    .banner-title {
      .platform-name {
        font-size: 24px;
        margin-bottom: 4px;
        letter-spacing: 1px;
      }

      .platform-desc {
        font-size: 14px;
      }
    }
  }

  .update-password-container {
    padding: 20px 15px;
  }

  .update-password-box {
    min-width: auto;
    padding: 30px 25px;
  }
}
</style>
